package web

import (
	"errors"
	"fmt"
	"goRss/appconfig"
	"goRss/module/source"
	"net/http"
	"reflect"
	"strconv"

	"github.com/labstack/echo"
)

func GetCH(c echo.Context) error {
	var data []appconfig.NewsCh = appconfig.AppConfig.Ch
	return c.JSON(http.StatusOK, data)

}

func GetNews(c echo.Context) error {

	var id, err = strconv.Atoi(c.QueryParam("id"))
	if err != nil {
		return errors.New("param id error")
	}
	var data []source.NEWS
	for _, ch := range appconfig.AppConfig.Ch {
		if ch.ID == id {
			data, err = loadNews(ch)
		}
		if err != nil {
			return err
		}
	}

	return c.JSON(http.StatusOK, data)

}

func loadNews(ch appconfig.NewsCh) (data []source.NEWS, err error) {
	// var api source.Api

	api, ok := source.NewStruct(ch.Type)
	if !ok {
		err = errors.New("type error")
		return
	}
	fmt.Println(api, reflect.TypeOf(api))
	t, ok := api.(source.Api)
	if !ok {
		err = errors.New("type error")
		return
	}

	data, err = t.FetchNews(ch.URL)
	return
}
